import { request, HttpResponse, HttpError } from './httpClient';
import { API_ENDPOINTS } from './apiConfig';

// 服务基类
export class BaseService {
  protected endpoints = API_ENDPOINTS;
  
  protected async request<T>(url: string, options: any = {}): Promise<T> {
    try {
      // 默认所有请求都需要认证
      const requestOptions = { requiresAuth: true, ...options };
      const response: HttpResponse<T> = await request<T>(url, requestOptions);
      return response.data;
    } catch (error: any) {  
      if (error instanceof HttpError) {
        // 可以在这里统一处理错误，如token过期等
        throw error;
      }
      throw new Error(`Network error: ${error?.message || 'Unknown error'}`);
    }
  }

  protected get<T>(url: string, options: any = {}): Promise<T> {
    return this.request<T>(url, { ...options, method: 'GET' });
  }

  protected post<T>(url: string, body?: any, options: any = {}): Promise<T> {
    return this.request<T>(url, { ...options, method: 'POST', body });
  }

  protected put<T>(url: string, body?: any, options: any = {}): Promise<T> {
    return this.request<T>(url, { ...options, method: 'PUT', body });
  }

  protected patch<T>(url: string, body?: any, options: any = {}): Promise<T> {
    return this.request<T>(url, { ...options, method: 'PATCH', body });
  }

  protected delete<T>(url: string, options: any = {}): Promise<T> {
    return this.request<T>(url, { ...options, method: 'DELETE' });
  }
}